package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

/**
 * Created by xiao zeng on 2017/6/28.
 */

@Controller
public class Upload {

    @RequestMapping("/up") //单文件上传
    public void uploads(@RequestParam("ufile") CommonsMultipartFile f , HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");

        String username =req.getParameter("user");
        System.out.println(username);

        String path = req.getSession().getServletContext().getRealPath("/upload/");
        File fi = new File(path);
        if (!fi.exists()){
            fi.mkdirs();
        }


        String name=f.getOriginalFilename();
        String ext = name.substring(name.lastIndexOf(".")).toLowerCase();
        String na = UUID.randomUUID().toString()+ext;
        f.transferTo(new File(path,na));

    }

    @RequestMapping("uploads.do") @ResponseBody //多文件上传
    public void uploads(@RequestParam("ufile") List<CommonsMultipartFile> f, HttpServletRequest req) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");
        for (CommonsMultipartFile ff : f){
            String name = ff.getOriginalFilename();
            if (!"".equals(name)){
                String path  = req.getServletContext().getRealPath("/upload/spring");
                File file = new File(path);
                if (!file.exists()){
                    file.mkdirs();
                }
                try {
                    ff.transferTo(new File(path,name));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
